package controller.specialty;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import service.SpecialtyService;
import service.impl.SpecialtyServiceImpl;
import controller.student.StudentServlet;
import util.BaseResult;
import vo.GetSpecialtyVO;

import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = "/getSpecialtyInfo")
public class GetSpecialtyInfoServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");

            String name = request.getParameter("name");

            SpecialtyService specialtyService = new SpecialtyServiceImpl();
            List<GetSpecialtyVO> voList = specialtyService.getSpecialtyInfo(name);

            BaseResult<List<GetSpecialtyVO>> result = BaseResult.success(voList);
            response.setContentType("application/json;charset=UTF-8");
            String jsonResponse = objectMapper.writeValueAsString(result);
            response.getWriter().write(jsonResponse);
        } catch (Exception e) {
            logger.error("获取专业信息错误", e);

            BaseResult<Void> errorResult = BaseResult.failed(500, "加载专业信息失败: " + e.getMessage());

            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

            String jsonError = objectMapper.writeValueAsString(errorResult);
            response.getWriter().write(jsonError);
        }
    }
}
